﻿@page "/MessageDefineInstance"

@namespace SageKing.Studio.Pages.SageKingMessage

@implements IMenuTab<SysMenu, long>
@implements IReuseTabsPage

@inject IMessageService _message
@inject IConfirmService _confirmService
@inject SysDictTypeService selectService

@inject SysMenuService _sysMenuService
@inject SysSageKingMessageInstanceService dataService
@inject SysSageKingMessageAttributeInstanceService dataDetailService

@using SageKing.Studio.Pages.SageKingMessage.component

<PageTitle>@TabTitle</PageTitle>

@if (pageData == null)
{
     <Spin size="SpinSize.Large" Tip="Loading..." />
}
else
{
    <Table @ref="table" TItem="SysSageKingMessageInstance"  Class="main-table" ScrollY="@BrowserConsts.ScrollYTable"
           DataSource="@pageData.Items"
           RowKey="x=>x.Id"
           OnRowClick="OnRowClick"
           @bind-SelectedRows="@selectedRows"
           Size="TableSize.Small"
           OnChange="OnChange"
           OnExpand="OnRowExpand" Loading="tableLoading"
           Resizable Bordered EnableVirtualization
           PageSize="pageData.PageSize">
        <TitleTemplate>
            <Space>
                <SpaceItem>
                    <Select @bind-Value="@searchModel.Type"
                            DataSource="@SelectSearchModelType.Children"
                            LabelName="@nameof(SysDictData.CodeValue)"
                            ValueName="@nameof(SysDictData.ValueInt)"
                            Style="min-width:150px; width: auto;"
                            TItemValue="int"
                            TItem="SysDictData"
                            Placeholder="请选消息类型"
                            AllowClear
                            EnableSearch>
                    </Select>
                </SpaceItem>
                <SpaceItem>
                    <Search Placeholder="消息名称" @bind-Value="searchModel.Name" OnSearch="async ()=>{await OnSearch(pageargs);Message(); }" AllowClear="true" />
                </SpaceItem>

                <SpaceItem>
                    <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Reload" OnClick="()=>SearchModelReSet()">重置</Button>
                </SpaceItem>
            </Space>
        </TitleTemplate>
        <ColumnDefinitions>
            <Selection Type="@selectionType"></Selection>
            <PropertyColumn Property="c=>c.Name" Title="消息名称" Sortable="true" Filterable />
            <PropertyColumn Property="c=>c.Type" Title="类型" Sortable="true" Align="ColumnAlign.Center" Filterable>
                <Text>@GetTypeDesc(context.Type)</Text>
            </PropertyColumn>
            <PropertyColumn Property="c=>c.Status" Title="状态" Align="ColumnAlign.Center" Sortable="true" Filterable>

            </PropertyColumn>
            <PropertyColumn Property="c=>c.Description" Title="描述信息" Ellipsis />
            <PropertyColumn Property="c=>c.Version" Title="Version" Sortable="true" Filterable></PropertyColumn>
            <PropertyColumn Property="c=>c.Id" Title="Id" Sortable="true" Filterable />
            <PropertyColumn Title="时间相关" Property="c=>c.CreateUserName" Align="ColumnAlign.Center">
                <Popover ContentTemplate="@baseRender.GetDetails(context)" Title="时间相关">
                    <Button Icon="@IconType.Outline.OrderedList" Shape="@ButtonShape.Circle" />
                </Popover>
            </PropertyColumn>
            <ActionColumn Title="消息操作" Align="ColumnAlign.Center">
                <Space>
                    <SpaceItem>
                        <Tooltip Title="发送，客户端向服务端发送消息。">
                            <Button OnClick="(e)=>skMessageFrmToSendModal.ShowSendData(context)" Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Send" />
                        </Tooltip>
                    </SpaceItem>
                    <SpaceItem>
                        <Tooltip Title="推送，服务端向客户端推送消息。">
                            <Button OnClick="(e)=>skMessageFrmToSendModal.ShowPushData(context)" Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Notification" />
                        </Tooltip>
                    </SpaceItem>
                    <SpaceItem>
                        <Tooltip Title="生成C# Entity代码">
                            <Button OnClick="async (e)=>await codeEditBoxModal.MeCrud.ShowAdd(context,false)" Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Code" />
                        </Tooltip>
                    </SpaceItem>
                </Space>
            </ActionColumn>
            <ActionColumn Title="Action" Fixed="ColumnFixPlacement.Right">
                <Space>
                    <SpaceItem>
                        <Popconfirm Title="清理生成代码本地缓存?"
                                    OnConfirm="(e) => codeEditBoxModal.ClearCacheCodeData(context)"
                                    OkText="Yes"
                                    CancelText="No">
                            <Button Icon="@IconType.Outline.Clear" Shape="@ButtonShape.Circle" Danger></Button>
                        </Popconfirm>
                    </SpaceItem>
                </Space>
            </ActionColumn>
        </ColumnDefinitions>
        <ExpandTemplate Context="rowData">
            <Table Class="childTable" TItem="SysSageKingMessageAttributeInstance" DataSource="rowData.Data.Children" Loading="rowData.Data.Children==null" Size=@TableSize.Small EnableVirtualization PageSize="10" ScrollY="200px" PaginationPosition="bottomCenter"
                   @bind-SelectedRows="@selectedRowsAttr" RowKey="a=>a.Id.ToString()" OnRowClick="OnRowAttrClick" Resizable Bordered>
                <ColumnDefinitions>
                    <Selection Key="@rowData.Data.Id.ToString()" Type="@selectionType"></Selection>
                    <PropertyColumn Property="c=>c.Name" Title="属性名称" Sortable="true" Filterable />
                    <PropertyColumn Property="c=>c.Type" Title="类型" Sortable="true" Align="ColumnAlign.Center" Filterable>
                        <Text>@context.Type.GetDescription(true)</Text>
                    </PropertyColumn>
                    <PropertyColumn Property="c=>c.Status" Title="Status" Sortable="true" Align="ColumnAlign.Center" Filterable>

                    </PropertyColumn>
                    <PropertyColumn Property="c=>c.Description" Title="描述信息" Ellipsis />
                    <PropertyColumn Property="c=>c.Id" Title="Id" Sortable="true" Filterable />
                    <PropertyColumn Property="c=>c.MessageId" Title="MessageId"></PropertyColumn>
                    <PropertyColumn Title="时间相关" Property="c=>c.CreateUserName" Align="ColumnAlign.Center">
                        <Popover ContentTemplate="@baseRender.GetDetails(context)" Title="时间相关">
                            <Button Icon="@IconType.Outline.OrderedList" Shape="@ButtonShape.Circle" />
                        </Popover>
                    </PropertyColumn>
                </ColumnDefinitions>
                <PaginationTemplate>
                    <Pagination Class="@(context.PaginationClass + " my-custom-pagination")"
                                Total="context.Total"
                                ShowTotal="baseRender.showTotal"
                                PageSize="context.PageSize"
                                Current="context.PageIndex"
                                ShowSizeChanger
                                OnChange="context.HandlePageChange" />
                </PaginationTemplate>
            </Table>
        </ExpandTemplate>


        <PaginationTemplate>
            <Pagination ShowTotal="baseRender.showTotal" Class="@(context.PaginationClass + " my-custom-pagination")"
                        Total="pageData.Total"
                        PageSize="pageData.PageSize"
                        Current="pageData.Page"
                        ShowSizeChanger
                        ShowQuickJumper
                        OnChange="OnSearch" />
        </PaginationTemplate>
    </Table>

    <Modal Title="@codeEditBoxModal.Title" Class="modelDefault" MaxBodyHeight="@("65vh")"
           @bind-Visible="@codeEditBoxModal.Visible" Draggable="@(true)" Centered Closable="false"
           OnOk="codeEditBoxModal.HandleOk" ConfirmLoading="codeEditBoxModal.Loading" OkText="codeEditBoxModal.OkTitle" CancelText="codeEditBoxModal.CancelText">

        @codeEditBoxModal.ModalTemplate
    </Modal>

    <Modal Title="@skMessageFrmToSendModal.Title" Class="modelDefault" MaxBodyHeight="@("65vh")" Resizable=true Width="888"
           @bind-Visible="@skMessageFrmToSendModal.Visible" Draggable="@(true)" Centered Closable="false"
           OnOk="skMessageFrmToSendModal.HandleOk" ConfirmLoading="skMessageFrmToSendModal.Loading" OkText="skMessageFrmToSendModal.OkTitle" CancelText="skMessageFrmToSendModal.CancelText">

        @skMessageFrmToSendModal.ModalTemplate
    </Modal>
}

@code {

    bool loading;
    bool IsfirstRender = false;

    BaseRenderFragment baseRender;

    //table
    ITable table;
    bool tableLoading;
     SelectionType selectionType = SelectionType.Checkbox;
    bool isOnRowExpand = false;

    //search
    SysSageKingMessageInstance searchModel;
    SysDictType SelectSearchModelType;

    PaginationEventArgs pageargs = new PaginationEventArgs(1, 10);
    PageBase<SysSageKingMessageInstance> pageData;

    IEnumerable<SysSageKingMessageInstance> selectedRows;
    IEnumerable<SysSageKingMessageAttributeInstance> selectedRowsAttr;

    //select data
    SysDictType SelectDataType;

    #region init
    #region menu

    public IMenuTab<SysMenu, long> MeTab { get { return this; } }

    public IBaseServiceCache<SysMenu, long> MenuService
    { get { return _sysMenuService; } }

    [SupplyParameterFromQuery(Name = "menuid")]
    public long menuid { get; set; }

    [Parameter]
    public string TabTitle { get; set; } = "消息结构定义";

    [Parameter]
    public string TabIcon { get; set; } = "home";

    public RenderFragment GetPageTitle() =>
    @<div>
        <Icon Type="@TabIcon" /> @TabTitle
    </div>
    ;
    #endregion

    [CascadingParameter]
    public Error? Error { get; set; }

    protected override async Task OnInitializedAsync()
    {
        try
        {
            baseRender = new BaseRenderFragment();

            await InitSelectData();
            await InitSeachMain();
            await InitModal();
            await Refresh(false);
            await MeTab.InitTabTitle();

        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex);
        }
    }

    async Task InitSeachMain()
    {
        searchModel = new SysSageKingMessageInstance();
        SelectSearchModelType = await selectService.GetDetailCache(SysDictTypeConst.code_message_type);

    }

    async Task InitSelectData()
    {
        SelectDataType = await selectService.GetDetailCache(SysDictTypeConst.code_message_type);
    }

    string? GetTypeDesc(int type)
    {
        return SelectDataType?.Children?.FirstOrDefault(a => a.ValueInt == type)?.CodeValue;
    }

    async Task InitModal()
    {
        initSageKingMessageFormEditModal();
        InitCodeEditBoxModal();

        await Task.CompletedTask;
    }

    #endregion

    async Task Refresh(bool notice = true)
    {
        await OnSearch(pageargs);
        if (isOnRowExpand)
        {
            table?.CollapseAll();
            isOnRowExpand = false;
        }
        if (notice)
        {
            _ = _message.SuccessAsync("刷新成功!");
        }
    }

    void SearchModelReSet()
    {
        searchModel = new SysSageKingMessageInstance();
    }

    public async Task OnSearch(PaginationEventArgs args)
    {
        tableLoading = true;
        pageargs.Page = args.Page;
        pageargs.PageSize = args.PageSize;

        var page = new PageBaseInput() { Page = pageargs.Page, PageSize = pageargs.PageSize };

        var whereIf = new List<(bool, Expression<Func<SysSageKingMessageInstance, bool>>)>();

        Expression<Func<SysSageKingMessageInstance, bool>> whereIffunc1 = a => a.Name.Contains(searchModel.Name);
        Expression<Func<SysSageKingMessageInstance, bool>> whereIffunc2 = a => a.Type == searchModel.Type;

        whereIf.Add((searchModel.Name.IsNotNullOrWhiteSpace(), whereIffunc1));
        whereIf.Add((searchModel.Type > 0, whereIffunc2));

        pageData = await dataService.GetPage(page, whereIf, a => a.Id, false);

        InitPageData();

        tableLoading = false;

        StateHasChanged();
    }

    void InitPageData()
    {
    } 

    public async Task<List<SysSageKingMessageAttributeInstance>> QueryChildList(long ParentId)
    {
        Expression<Func<SysSageKingMessageAttributeInstance, bool>> func = a => a.MessageId == ParentId;
        Expression<Func<SysSageKingMessageAttributeInstance, object>> orderbyfunc = a => a.Id;

        var result = await dataDetailService.GetList(func, orderbyfunc, false);

        return result;
    }

    private async void OnRowClick(RowData<SysSageKingMessageInstance> data)
    {
        var row = data.Data;
        await QueryChildList(row.Id);
    }

    private void OnRowAttrClick(RowData<SysSageKingMessageAttributeInstance> data)
    {
        var row = data.Data;
    }

    private async void OnRowExpand(RowData<SysSageKingMessageInstance> data)
    {
        isOnRowExpand = true;
        data.Data.Children = await QueryChildList(data.Data.Id);
        StateHasChanged();
    }

    void OnChange(QueryModel<SysSageKingMessageInstance> query)
    {
        var dd = query;
    }


    void Message(string msg = "查询成功")
    {
        _ = _message.SuccessAsync(msg);
    }
}

@code {
    //消息操作，用于发送，及推送
    [Inject]
    SageKingMessageFormEditModal<SysSageKingMessageInstance, SysSageKingMessageAttributeInstance> skMessageFrmToSendModal { get; set; }

    void initSageKingMessageFormEditModal()
    {
        skMessageFrmToSendModal.Error = Error;

        skMessageFrmToSendModal.TabTitle = TabTitle;

        skMessageFrmToSendModal.ModalTemplate = @<SageKingMessageFormEdit @ref="@skMessageFrmToSendModal.Component" model="@skMessageFrmToSendModal.Model"></SageKingMessageFormEdit>;

        skMessageFrmToSendModal.GetTypeDescFunc = GetTypeDesc;
        skMessageFrmToSendModal.QueryChildListFunc = QueryChildList;
    }
}

@code {

    //代码生成显示
    [Inject]
    CodeEditBoxModal<SysSageKingMessageInstance, SysSageKingMessageAttributeInstance> codeEditBoxModal { get; set; }

    void InitCodeEditBoxModal()
    {
        codeEditBoxModal.Error = Error;

        codeEditBoxModal.TabTitle = TabTitle;

        codeEditBoxModal.ModalTemplate = @<CodeEditBox markdownValue="@codeEditBoxModal.Model" isShow="true" @ref="@codeEditBoxModal.Component"></CodeEditBox>;

        codeEditBoxModal.GetTypeDescFunc = GetTypeDesc;
        codeEditBoxModal.QueryChildListFunc = QueryChildList;
        codeEditBoxModal.StateHasChanged = StateHasChanged;
    }
}

